<template>
  <div ref="chartRef" style="width: 600px; height: 400px;"></div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import * as echarts from 'echarts';
import { faker } from '@faker-js/faker/locale/zh_CN';

const chartRef = ref(null);
let chartInstance = null;

// 生成最近15天的日期
function generateLast15Days() {
  const dates = [];
  for (let i = 14; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    dates.push(date.toISOString().split('T')[0]);
  }
  return dates;
}

// 生成模拟数据
function generateMockData() {
  const dates = generateLast15Days();
  return dates.map(date => ({
    date: date.split('-').slice(1).join('-'), // 只显示月-日
    value: faker.number.int({ min: 8, max: 25 }) // 每天8-25个帖子
  }));
}

// 图表配置
function getChartOption(chartData) {
  return {
    title: {
      text: '近15天物资捐赠趋势'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: chartData.map(item => item.date)
    },
    yAxis: {
      type: 'value',
      name: '帖子数量'
    },
    series: [{
      name: '帖子数量',
      type: 'line',
      smooth: true,
      data: chartData.map(item => item.value),
      areaStyle: {
        opacity: 0.3,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(91, 192, 192, 0.5)'
          },
          {
            offset: 1,
            color: 'rgba(91, 192, 192, 0.1)'
          }
        ])
      },
      itemStyle: {
        color: '#5BC0C0'
      }
    }]
  };
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  // 使用模拟数据
  const chartData = generateMockData();

  chartInstance = echarts.init(chartRef.value);
  chartInstance.setOption(getChartOption(chartData));
}

// 响应式调整
function resizeChart() {
  chartInstance?.resize();
}

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  chartInstance?.dispose();
});
</script>
